import iotUtils
import ter
import time
from  datetime import  datetime , timedelta
import threading
import requests
class TBusCalculateWx( ter.TIotBus):
    def __init__(self , ter ):
        super().__init__(ter)

    def init (self):
        try:
            super().init()
        except Exception as er:
            print(er)
    def start (self):
        try:
            self.running = True
            taskList = list(self.tasks.values())
            taskIndex = -1
            while   len(taskList)>0  and  self.running  :
                try:
                    nowTm = time.time()
                    taskIndex = taskIndex + 1
                    if taskIndex>= len(taskList):
                        taskIndex = 0
                    task = taskList[taskIndex]
                    taskLastTime = task['lastTm']
                    frequency = task['frequency']
                    flag = nowTm - taskLastTime > frequency
                    if flag :
                        task['lastTm'] = nowTm
                        status , y , m , d = self.getPower()
                        if status ==1 :
                            registerBytes =[y , m , d ]
                            self.doOnTask(task , registerBytes)
                except Exception as eer:
                    print(eer)
        except Exception as er:
            print(er)
    def stop (self):
        try:
            self.running = False
        except Exception as er:
            print(er)
    #根据电表的数据来计算
    def getPower_(self):
        status =0
        y=0
        m=0
        d=0
        try:
            nowDt = datetime.now()
            dtEnd = nowDt+timedelta(hours=-8)
            dtFromYear = datetime( nowDt.year ,1 , 1) + timedelta(hours=-8)
            dtFromMonth = datetime( nowDt.year ,nowDt.month , 1) + timedelta(hours=-8)
            dtFromDay = datetime( nowDt.year ,nowDt.month , nowDt.day) + timedelta(hours=-8)
            def query (dt):
                status = 0
                res = 0
                try:
                    dtStr = dt.strftime('%Y-%m-%dT%H:%M:%SZ')
                    sql =f"select  last(v) - first(v) as v   from wx64501 where vid='567' and time >='{dtStr}'  order by time"
                    url = self.ter.terData['terInfo']['tdbUrl']
                    db = self.ter.terData['terInfo']['tdbDB']
                    token = self.ter.terData['terInfo']['tdbToken']
                    headers = {
                        "Authorization": token,
                        'Content-Type': 'application/json',
                    }
                    influxdb_url = url + '/query?db=' + db
                    influxdb_url = influxdb_url + "&q=" + sql
                    resp = requests.get(url=influxdb_url, headers=headers)
                    resJson = resp.json()
                    res = resJson['results'][0]['series'][0]['values'][0][1]
                    status = 1
                except Exception as er1 :
                    print(er1)
                return status , res
            status , y = query(dtFromYear)
            status , m = query(dtFromMonth)
            status , d = query(dtFromDay)
        except Exception as er:
            print(er)
        return status , y, m , d
    #根据逆变器数据来计算
    def getPower(self):
        status =0
        y=0
        m=0
        d=0
        try:
            url = self.ter.apiUrl+"/iotCalculate/9001"
            resp = requests.get(url)
            res = resp.json()
            if res['s'] == 1:
                y = res['y']
                m = res['m']
                d = res['d']
                status=1
        except Exception as er:
            print(er)
        return status , y, m , d

ter.iotTer.registBusType('calculateWx' , TBusCalculateWx)